﻿using EnetaMvc.ApplicationServices.Dto;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EnetaMvc.Web.Extensions
{
    public static class EnetaDtoExtensions
    {
        public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> dtos) where T : BaseDto
        {
            return ToSelectList(dtos, -1);
        }

        public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> dtos, long selectedValue) where T : BaseDto
        {
            var items = from dto in dtos
                        select new SelectListItem
                        {
                            Value = dto.Id.ToString(),
                            Text = dto.ToString(),
                            Selected = (dto.Id == selectedValue)
                        };
            return items.ToList();
        }

        public static string GetShortTitle(this ForumPostDto dto, int maxLength = 15)
        {
            if (dto == null)
                return null;
            if (string.IsNullOrEmpty(dto.Title))
                return null;

            if (dto.Title.Length <= maxLength)
                return dto.Title;

            return dto.Title.Substring(0, maxLength - 3) + "...";
        }

        public static string GetTextAbstract(this ForumPostDto dto)
        {
            var body = Util.StripTags(dto.Body);
            body = HttpContext.Current.Server.HtmlDecode(body);

            if (body.Length < 150)
                return body;

            return body.Substring(0, 150) + "...";
        }
    }
}